<template>
  <div>
    <div class="card-header">
      <span>内部人员</span>
      <el-divider></el-divider>
    </div>
    <el-row>
      <el-col :span="24" align="right">
<!--        <el-button type="primary" @click="addPeople()">添加人员</el-button>-->
      </el-col>
    </el-row>
    <Table :tableArr="inMember" :pagination="data.page" :columns="data.columns">
      <template #operate="{ row }">
<!--        <el-button size="small" type="danger" @click="handleEdit(row)">编辑</el-button>-->
<!--        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>-->
      </template>
    </Table>
    <div class="card-header">
      <span>外部人员</span>
      <el-divider></el-divider>
    </div>
    <Table :tableArr="outMember" :pagination="data.page" :columns="data.columns">
      <template #operate="{ row }">
<!--        <el-button size="small" type="danger" @click="handleEdit(row)">编辑</el-button>-->
<!--        <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>-->
      </template>
    </Table>


    <el-dialog v-model="data.addPeople" append-to-body width="50%" :show-close="false"
      :close-on-click-modal="false">
      <template #title>
        <div class="my-header">
          <el-tabs v-model="data.activeName" class="demo-tabs">
            <el-tab-pane label="添加人员" name="first">
              <el-form v-model="data.addPeople" append-to-body width="800px" label-width="110px" top="10vh"
                :show-close="false" :close-on-click-modal="false">
                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="人员类型：">
                      <SelectOption :selectValue="form.unitType" :options="data.unitTypeList"
                        @change-value="changeValue0">
                      </SelectOption>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="所属单位：">
                      <el-input type="text" v-model="form.unit" v-if="form.unitType == '1'"
                        @change="form.unitId = form.unit" placeholder="请输入所属单位"></el-input>
                      <!-- <popup-tree-input :data="data.popupTreeData" v-else :props="data.popupTreeProps" :prop="data.deptForm.parentName == null
                        ? $t('message.org.top_menu')
                        : form.unit
                        " :node-key="'' + data.deptForm.parentId" :current-change-handle="changeValue7" /> -->
                      <popup-tree-input v-esle :data="data.popupTreeData" :props="data.popupTreeProps" :prop="data.deptForm.parentName == null
                          ? $t('message.org.top_menu')
                          : form.unit
                        " :node-key="'' + data.deptForm.parentId" :current-change-handle="changeValue7" v-else/>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="人员排名：">
                      <el-input-number v-model="form.sort" :step="1" style="width: 100%" :min="1"></el-input-number>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="人员姓名：">
                      <el-input type="text" v-model="form.memberName" v-if="form.unitType == '1'" placeholder="联系人"
                        maxlength="15"></el-input>
                      <!-- <SelectOption :selectValue="form.memberId" :options="data.peopleList" @change-value="changeValue1"
                        v-else></SelectOption> -->
                      <user-list-modal v-model="form.memberName" @update:modelValue="changeValue1" :default-users="[]"
                        :multiple="false" :devType="'platform'" v-else />
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="40">
                  <el-col :span="12">
                    <el-form-item label="性别：">
                      <SelectOption :selectValue="form.sex" :options="data.sexList" @change-value="changeValue2">
                      </SelectOption>
                    </el-form-item>
                  </el-col>

                  <el-col :span="12">
                    <el-form-item label="职称：">
                      <el-input type="text" v-model="form.professionalPost" v-if="form.unitType == '1'"
                        placeholder="请输入职称" maxlength="15"></el-input>
                      <SelectOption :selectValue="form.professionalPost" :options="data.roleList"
                        @change-value="changeValue3" v-else></SelectOption>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="close">关闭</el-button>
          <el-button type="primary" @click="save()">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import * as proxy from '@/constants/proxy'
import request from '@/utils/request'
import UserListModal from '@/views/project/components/UserListModal/index.vue'
import common from '@/views/science/common/common.json'
import PopupTreeInput from '@/views/science/components/PopupTreeInput/index.vue'
import SelectOption from '@/views/science/components/selectOption/index.vue'
import Table from '@/views/science/components/table/table.vue'
import { Modals } from '@/views/science/components/tips/tips'
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useStore } from 'vuex'

export default {
  components: {
    Table,
    SelectOption,
    PopupTreeInput,
    UserListModal,
  },
  emits: {
    dataChange: null,
    paramsChangeInMember: null,
    paramsChangeOutMember: null,
  },
  props: {
    inMember: {
      type: Array,
      required: true,
    },

    outMember: {
      type: Array,
      required: true,
    },
    membersFlag: {
      type: Boolean,
      required: true,
    },
  },
  setup(props, { emit }) {

    const inMember = ref(props.inMember)

    watch(props, (newValue, oldValue) => {
      inMember.value = newValue.inMember
    });


    const outMember = ref(props.inMember)

    watch(props, (newValue, oldValue) => {
      outMember.value = newValue.outMember
    });



    const store = useStore()
    const value = ref([])
    let data = reactive({
      activeName: ref('first'),
      columns: common.platformMemberInfoHeader,
      page: {
        page: 1,
        limit: 10,
        total: 0,
      },
      editItem: {},

      addType: 'add',

      addPeople: false,

      deptForm: {
        parentId: 0,
        parentName: "",
      },

      unitTypeList: [
        { id: "0", name: "内部人员" },
        { id: "1", name: "外部人员" },
      ],
      sexList: [
        { id: "0", name: "男" },
        { id: "1", name: "女" },
      ],

      usersSelet: [],
      roleList: [],
      peopleList: [],
      popupTreeData: [],
      popupTreeProps: {
        label: 'name',
        children: 'children',
      },
      parentId: 0,
      tableTreeData: [
        {
          children: [],
          dictName: '',
          id: undefined,
        },
      ],
    })


    const selOp = computed(() => {
      const obj = store.state.technologyStrength.unitSelet
      let arr = [] as any
      for (let key in obj) {
        arr.push(obj[key])
      }
      return arr
    })


    // 内部人员  外部人员

    // const inMember = ref([] as any)

    // const outMember = ref([] as any)

    const form = reactive({

      unitType: '' as any,// 人员类型

      sex: '' as any,
      sexName: '' as any,

      professionalPost: '',

      professionalPostId: '',

      unit: '' as any,
      unitId: '' as any,
      memberId: '' as any,

      memberName: "" as any,
      sort: 0 as any,
    })


    //
    const changeValue7 = (item) => {

      form.unit = item.name;

      form.unitId = item.id;

    }

    // 选择内部人员的时候

    const changeValue0 = async (item) => {

      form.unitType = item.id
    }


    // 人员姓名

    const changeValue1 = (item) => {
      form.memberId = item.userId
      form.memberName = item.cname
    }

    const changeValue2 = (item) => {


      form.sex = item.id

      form.sexName = item.name

    }


    // 职称选择
    const changeValue3 = (item) => {

      form.professionalPostId = item.itemValue

      form.professionalPost = item.itemText
    }


    const addPeople = () => {
      data.addType = "add";
      data.addPeople = true
    }

    const findItemNested = (arr, itemId, nestingKey) => (
      arr.reduce((a, item) => {
        if (a) return a;
        if (item.id === itemId) return item;
        if (item[nestingKey]) return findItemNested(item[nestingKey], itemId, nestingKey)
      }, null)
    );

    const handleChange = (value) => {
      const item = findItemNested(selOp.value, value, 'children')
      changeValue0(item)
    }

    const save = async () => {

      // 内部

      if (form.unitType == 0) {

        if (data.addType == "add") {

          inMember.value.unshift(JSON.parse(JSON.stringify(form)));

        } else {

          var index = inMember.value.indexOf(data.editItem);

          console.log(index)

          if (index > -1) {

            inMember.value[index] = JSON.parse(JSON.stringify(form));

          }
        }



        emit("paramsChangeInMember", inMember.value);

        data.addPeople = false;

      }

      // 外部

      if (form.unitType == 1) {

        if (data.addType == "add") {

          outMember.value.unshift(JSON.parse(JSON.stringify(form)));

        } else {

          var index = outMember.value.indexOf(data.editItem);

          console.log(index)

          if (index > -1) {

            outMember.value[index] = JSON.parse(JSON.stringify(form));

          }
        }

        emit("paramsChangeOutMember", outMember.value);

        data.addPeople = false;
      }
      close()
    }

    const handleDelete = async (row) => {
      if (row.unitType == 0) {

        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          var index = inMember.value.indexOf(row);
          if (index > -1) {
            //大于0 代表存在，
            inMember.value.splice(index, 1); //存在就删除
          }
          emit("paramsChangeInMember", inMember.value);
        }).catch(() => {
          console.log("点击了取消")
        })

      }

      // 外部人员删除

      if (row.unitType == 1) {

        Modals('是否删除选择内容', '提示', 'warning').then(async () => {
          var index = outMember.value.indexOf(row);
          if (index > -1) {
            //大于0 代表存在，
            outMember.value.splice(index, 1); //存在就删除
          }
          emit("paramsChangeOutMember", outMember.value);
        }).catch(() => {
          console.log("点击了取消")
        })

      }


    }
    const handleEdit = (row) => {

      data.addType = "edit";
      Object.assign(form, row);
      data.editItem = row;
      data.addPeople = true;

    }

    const findTreeData = async () => {

      return request({
        url: proxy.CHECC_API_CMS + "/org/getSysOrgList",
        method: "get",
      }).then(res => {
        data.popupTreeData = res.data.data
      })
      // let res = await getOrgTree()
      // //获取上级机构
      // data.popupTreeData = res.data.data
    }
    // 字典
    const affiliation = async () => {
      request({
        url: proxy.CHECC_API_CMS + '/dictItem/codelist',
        method: 'post',
        data: ["KJSL_MEMBER_ROLE"]
      }).then((res) => {
        data.roleList = res.data.data.KJSL_MEMBER_ROLE
      })
    }


    //人员列表
    const getRoleList = async () => {
      request({
        url: proxy.CHECC_API_CMS + "/user/getAll",
        method: "get",
      }).then((res) => {
        data.peopleList = res.data.data
      })
    }

    onMounted(() => {
      findTreeData()
      affiliation()
      getRoleList()

    });


    // watch(
    //   () => props.inMember,
    //   (newValue, oldValue) => {
    //     if (props.membersFlag) {
    //       inMember.value.length = 0;
    //       if (newValue.length > 0) {
    //         newValue.forEach((e) => {
    //           inMember.value.unshift(e);
    //         });
    //       }

    //     }
    //   },
    // );


    // watch(
    //   () => props.outMember,
    //   (newValue, oldValue) => {
    //     if (props.membersFlag) {
    //       inMember.value.length = 0;
    //       if (newValue.length > 0) {
    //         newValue.forEach((e) => {
    //           inMember.value.unshift(e);
    //         });
    //       }

    //     }
    //   },
    // );
    const close = () => {
      data.addPeople = false
      form.unitType = ''
      form.sex = ''
      form.sexName = ''
      form.professionalPost = ''
      form.professionalPostId = ''
      form.unit = '' as any
      form.unitId = '' as any
      form.memberId = '' as any
      form.memberName = "" as any
      form.sort = 0 as any
    }

    return {
      data,
      form,
      changeValue7,
      inMember,
      outMember,
      value,
      changeValue3,
      handleChange,
      selOp,
      handleEdit,
      addPeople,
      close,
      handleDelete,
      save,
      changeValue0,
      changeValue1,
      changeValue2,
      findTreeData,
      affiliation,
    }
  },
}
</script>

<style scoped lang="scss">
.demo-form-inline .el-form-item {
  width: 70%;
}

.el-select {
  width: 100%;
  margin: 0;
}

.card-header {
  font-size: 16px;
  font-weight: bold;
  margin-top: 10px;
}
</style>
